package com.xiaoger.jwt.config;

import com.xiaoger.jwt.util.JwtUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * JWT拦截器
 *
 * @author xjx
 * @date 2022/5/14 11:14
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从http请求头中取出token
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //查看请求的方法上边带没带自定义Token注解
        if (method.isAnnotationPresent(Token.class)) {
            Token annotation = method.getAnnotation(Token.class);
            if (token == null) {
                //没有携带token
                response.setContentType("application/json; charset=UTF-8");
                response.getWriter().print("请携带token访问！");
                return false;
            }
            //验证token是否过期
            if (JwtUtil.isExpired(token)) {
                throw new RuntimeException("token过期");
            }
            // 验证 token是否正确
            //这里可以去数据库查询当前的用户密码,这里就简单写一下
            String password = "123456";
            if (!JwtUtil.verify(token, JwtUtil.getUsername(token), password)) {
                response.setContentType("application/json; charset=UTF-8");
                response.getWriter().print("token错误！");
            }

            //模拟访问权限
            if ("1".equals(annotation.value())) {
                //为了方便此处使用username充当角色
                String username = JwtUtil.getUsername(token);
                if ("admin".equals(username)) {
                    return true;
                } else {
                    response.setContentType("application/json; charset=UTF-8");
                    response.getWriter().print("权限不足，无法访问！");
                }
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
